package com.codemart.service.impl;

import com.codemart.constant.JwtHeaderConstant;
import com.codemart.constant.MessageConstant;
import com.codemart.dto.UserDetailDTO;
import com.codemart.dto.UserUpdatePasswordDTO;
import com.codemart.dto.UsernameAndPasswordDTO;
import com.codemart.entity.UsernameAndPasswordEntity;
import com.codemart.exception.BaseException;
import com.codemart.exception.LoginFailedException;
import com.codemart.mapper.UserDetailMapper;
import com.codemart.mapper.UserInfoMapper;
import com.codemart.service.UserDetailService;
import com.codemart.util.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserDetailServiceImpl implements UserDetailService {

    @Autowired
    UserDetailMapper userDetailMapper;

    @Autowired
    UserInfoMapper userInfoMapper;

    @Override
    public UserDetailDTO getUserDetail(HttpServletRequest request) {
        String token = request.getHeader(JwtHeaderConstant.TOKEN_NAME_LOWER);
        if (token != null) {
            Integer userid;
            try {
                Claims claims = JwtUtil.parseJWT(token);
                userid = Integer.valueOf(claims.getSubject());
            } catch (Exception e) {
                throw new LoginFailedException(MessageConstant.LOGIN_INFORMATION_IS_INCORRECT);
            }
            UserDetailDTO userDetail = userDetailMapper.getUserDetail(userid);
            return userDetail;
        }else{
            return null;
        }
    }

    @Override
    public void updatePassword(HttpServletRequest request,UserUpdatePasswordDTO userUpdatePasswordDTO) {
        String token = request.getHeader(JwtHeaderConstant.TOKEN_NAME_LOWER);
        Integer userid;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userid = Integer.valueOf(claims.getSubject());
        } catch (Exception e) {
            throw new LoginFailedException(MessageConstant.LOGIN_INFORMATION_IS_INCORRECT);//登录信息有误
        }
        UsernameAndPasswordDTO userPassword = userInfoMapper.getUserPassword(userid);
        if(userPassword.getPassword().equals(userUpdatePasswordDTO.getOldPWD())){
            UsernameAndPasswordEntity usernameAndPasswordEntity = new UsernameAndPasswordEntity();
            usernameAndPasswordEntity.setUId(userid);
            usernameAndPasswordEntity.setPassword(userUpdatePasswordDTO.getNewPWD());

            userDetailMapper.updatePasswordByUser(usernameAndPasswordEntity);
        }else{
            throw new BaseException(MessageConstant.OLD_PASSWORD_IS_ERROR);
        }

    }
}
